<template>
  <div class="codes-page">
    <div class="page-header">
      <h2>
        <el-icon><Postcard /></el-icon>
        商品编码管理
      </h2>
      <el-button type="primary" @click="handleAddCode">
        <el-icon><Plus /></el-icon>
        添加编码
      </el-button>
    </div>

    <el-card>
      <template #header>
        <div class="card-header">
          <span>编码列表</span>
          <el-input
            v-model="searchText"
            placeholder="搜索商品或编码..."
            clearable
            style="width: 300px"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
      </template>

      <el-table :data="filteredCodes" stripe>
        <el-table-column prop="productCode" label="商品编码" width="120" />
        <el-table-column prop="productName" label="商品名称" min-width="150" />
        <el-table-column label="条形码" width="150">
          <template #default="{ row }">
            <div class="code-cell">
              <el-icon><Postcard /></el-icon>
              <span>{{ row.barcode || '-' }}</span>
              <el-button
                v-if="row.barcode"
                type="primary"
                size="small"
                text
                @click="handleCopyCode(row.barcode)"
              >
                复制
              </el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="EAN-13" width="150">
          <template #default="{ row }">
            <div class="code-cell">
              {{ row.ean13 || '-' }}
              <el-button
                v-if="row.ean13"
                type="primary"
                size="small"
                text
                @click="handleCopyCode(row.ean13)"
              >
                复制
              </el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="supplierCode" label="供应商编码" width="120" />
        <el-table-column prop="customCode" label="自定义编码" width="120" />
        <el-table-column label="二维码" width="100">
          <template #default="{ row }">
            <el-button type="success" size="small" @click="handleGenerateQR(row)">
              生成
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" text @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="success" size="small" text @click="handlePrint(row)">
              打印
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 编辑编码对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="700px">
      <el-form :model="codeForm" label-width="120px">
        <el-form-item label="商品">
          <el-select v-model="codeForm.productId" placeholder="请选择商品" style="width: 100%" filterable>
            <el-option
              v-for="product in products"
              :key="product.id"
              :label="`${product.code} - ${product.name}`"
              :value="product.id"
            />
          </el-select>
        </el-form-item>

        <el-divider>条形码</el-divider>
        <el-form-item label="条形码">
          <el-input v-model="codeForm.barcode" placeholder="请输入13位条形码">
            <template #append>
              <el-button @click="handleGenerateBarcode">自动生成</el-button>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="EAN-13">
          <el-input v-model="codeForm.ean13" placeholder="请输入EAN-13编码">
            <template #append>
              <el-button @click="handleGenerateEAN">自动生成</el-button>
            </template>
          </el-input>
        </el-form-item>

        <el-divider>其他编码</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="供应商编码">
              <el-input v-model="codeForm.supplierCode" placeholder="供应商提供的编码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="自定义编码">
              <el-input v-model="codeForm.customCode" placeholder="企业内部编码" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="国际编码">
              <el-input v-model="codeForm.internationalCode" placeholder="如UPC等" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="ISBN编码">
              <el-input v-model="codeForm.isbn" placeholder="图书类商品" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider>编码规则</el-divider>
        <el-form-item label="编码规则">
          <el-select v-model="codeForm.codeRule" placeholder="选择编码规则" style="width: 100%">
            <el-option label="按分类编码" value="category" />
            <el-option label="按时间编码" value="time" />
            <el-option label="按序号编码" value="sequence" />
            <el-option label="自定义规则" value="custom" />
          </el-select>
        </el-form-item>

        <el-form-item label="编码前缀">
          <el-input v-model="codeForm.codePrefix" placeholder="如：PRD、PROD等" style="width: 200px" />
        </el-form-item>

        <el-form-item label="流水号长度">
          <el-input-number v-model="codeForm.sequenceLength" :min="3" :max="10" style="width: 200px" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 二维码展示对话框 -->
    <el-dialog v-model="qrDialogVisible" title="商品二维码" width="400px">
      <div class="qr-container">
        <div ref="qrCodeRef" class="qr-code"></div>
        <div class="qr-info">
          <p><strong>商品：</strong>{{ currentProduct.productName }}</p>
          <p><strong>编码：</strong>{{ currentProduct.productCode }}</p>
          <p><strong>条码：</strong>{{ currentProduct.barcode }}</p>
        </div>
      </div>
      <template #footer>
        <el-button @click="qrDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="handleDownloadQR">下载二维码</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Postcard, Plus, Search } from '@element-plus/icons-vue'

const searchText = ref('')
const dialogVisible = ref(false)
const qrDialogVisible = ref(false)
const qrCodeRef = ref()

const products = ref([
  { id: 1, code: 'P001', name: 'iPhone 15' },
  { id: 2, code: 'P002', name: 'MacBook Pro' }
])

const productCodes = ref([
  {
    id: 1,
    productCode: 'P001',
    productName: 'iPhone 15',
    barcode: '6901234567890',
    ean13: '6901234567890',
    supplierCode: 'APL-IP15-001',
    customCode: 'PROD-2024-001',
    internationalCode: '',
    isbn: ''
  },
  {
    id: 2,
    productCode: 'P002',
    productName: 'MacBook Pro',
    barcode: '6901234567891',
    ean13: '6901234567891',
    supplierCode: 'APL-MBP-002',
    customCode: 'PROD-2024-002',
    internationalCode: '',
    isbn: ''
  }
])

const currentProduct = ref({})

const codeForm = reactive({
  productId: null,
  barcode: '',
  ean13: '',
  supplierCode: '',
  customCode: '',
  internationalCode: '',
  isbn: '',
  codeRule: 'category',
  codePrefix: 'PROD',
  sequenceLength: 6
})

const filteredCodes = computed(() => {
  if (!searchText.value) return productCodes.value
  return productCodes.value.filter(code => 
    code.productName.includes(searchText.value) ||
    code.productCode.includes(searchText.value) ||
    code.barcode?.includes(searchText.value) ||
    code.ean13?.includes(searchText.value)
  )
})

const dialogTitle = computed(() => codeForm.id ? '编辑编码' : '添加编码')

const handleAddCode = () => {
  Object.assign(codeForm, {
    id: null,
    productId: null,
    barcode: '',
    ean13: '',
    supplierCode: '',
    customCode: '',
    internationalCode: '',
    isbn: '',
    codeRule: 'category',
    codePrefix: 'PROD',
    sequenceLength: 6
  })
  dialogVisible.value = true
}

const handleEdit = (row) => {
  Object.assign(codeForm, { ...row })
  dialogVisible.value = true
}

const handleCopyCode = (code) => {
  navigator.clipboard.writeText(code)
  ElMessage.success('编码已复制')
}

const handleGenerateBarcode = () => {
  // 生成13位条形码（EAN-13格式）
  const prefix = '690' // 中国商品条码前缀
  const random = Math.floor(Math.random() * 10000000000).toString().padStart(9, '0')
  const code = prefix + random
  // 计算校验位
  let sum = 0
  for (let i = 0; i < 12; i++) {
    sum += parseInt(code[i]) * (i % 2 === 0 ? 1 : 3)
  }
  const checkDigit = (10 - (sum % 10)) % 10
  codeForm.barcode = code + checkDigit
  ElMessage.success('条形码已生成')
}

const handleGenerateEAN = () => {
  codeForm.ean13 = codeForm.barcode
  ElMessage.success('EAN-13已生成')
}

const handleGenerateQR = (row) => {
  currentProduct.value = row
  qrDialogVisible.value = true
  // 这里应该使用 qrcode.js 或类似库生成二维码
  ElMessage.info('二维码生成功能需要集成qrcode库')
}

const handlePrint = (row) => {
  ElMessage.info('打印功能开发中')
}

const handleDownloadQR = () => {
  ElMessage.success('二维码已下载')
}

const handleSubmit = () => {
  ElMessage.success('保存成功')
  dialogVisible.value = false
}
</script>

<style scoped>
.codes-page {
  padding: 20px;
  background: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 8px;
}

.page-header h2 {
  margin: 0;
  display: flex;
  align-items: center;
  gap: 10px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.code-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.qr-container {
  text-align: center;
  padding: 20px;
}

.qr-code {
  margin: 0 auto 20px;
  width: 200px;
  height: 200px;
  border: 1px solid #dcdfe6;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f5f5;
}

.qr-info {
  text-align: left;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 4px;
}

.qr-info p {
  margin: 8px 0;
  color: #606266;
}
</style>

